package controllers

import java.io.File

import akka.stream.Materializer
import akka.stream.scaladsl.Sink
import akka.util.ByteString
import javax.inject.Inject
import org.apache.commons.io.FileUtils
import org.apache.commons.lang3.StringUtils
import play.api.libs.json.Json
import play.api.libs.ws.WSClient
import play.api.mvc.{AbstractController, ControllerComponents}
import utils.Implicits._
import utils.Utils

import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global
import implicits.Implicits._

import scala.concurrent.Future
import scala.language.postfixOps


/**
 * Created by Administrator on 2019/8/27
 */
class TestController @Inject()(cc: ControllerComponents, ws: WSClient)(implicit materializer: Materializer) extends
  AbstractController(cc) {

  def test = Action { implicit request =>
    val parent = new File("D:\\ip4m_database\\user\\3\\mission\\613\\workspace\\1_vs_2\\09\\01")
    val dir = new File(parent, "Sig_Pathway")
    val jsDir = new File(Utils.dataDir, "js")
    FileUtils.copyDirectoryToDirectory(jsDir, dir)
    val contextFile = new File(parent, "red_hmdb_id.txt")
    val contextMap = contextFile.lines.drop(1).mapOtherByColumns { columns =>
      (columns(0) -> columns(1))
    }.toMap
    dir.listFiles().foreach { file =>
      if (file.isFile && file.getName.endsWith(".json")) {
        val fileName = file.getName
        val jsonStr = file.str
        val prefix = file.namePrefix
        val htmlFile = new File(dir, s"${prefix}.html")
        val context = contextMap.getOrElse(prefix, "")
        println(context)
        views.html.sigmaTemplate(jsonStr, fileName, context).toString().toFile(htmlFile)
      }
    }
    Ok("success!")
  }

  def sigmaJs = Action { implicit request =>
    val parent = new File("D:\\ip4m")
    val htmlFile = new File(parent, "out.html")
    val jsonFile = new File(parent, "data.json")
    val jsonStr = jsonFile.str
    val title = "Alanine Metabolism"
    val context = "HMDB0000243,HMDB0000123"
    views.html.sigmaTemplate(jsonStr, title, context).toString().toFile(htmlFile, encoding = null)
    Ok(views.html.test(jsonStr, title, context))
  }

  def ipathTest = Action.async { implicit request =>
    val startTime = System.currentTimeMillis()
    val parent = new File("C:\\workspaceForIDEA\\ip4m\\server\\pyScripts")
    val nameFile = new File(parent, "name_map.csv")
    implicit val sep = ","
    //    val names = nameFile.lines.trimQuote.selectOneColumn("kegg").notEmptyLines
    val names = List[String]()
    val groupFile = new File(parent, "true_SampleInfo.csv")
    val groupSize = groupFile.lines.trimQuote.selectOneColumn("classnote").distinct.notEmptyLines.size
    val defaultColor = "#FF0000"
    val colorMap = if (groupSize < 3) {
      val fcFile = new File(parent, "Potential_Biomarkers.csv")
      val fcMap = fcFile.lines.trimQuote.lineMap.map { map =>
        val fc = map("fc").toDouble
        val logFc = Utils.log2(fc)
        (map("kegg"), logFc)
      }.toMap
      fcMap.map { case (keggId, logFc) =>
        val color = if (logFc > 0) "red" else "blue"
        val webColor = color match {
          case "red" => "#FF0000"
          case "blue" => "#0000FF"
        }
        (keggId, webColor)
      }
    } else Map[String, String]()
    val nameStr = names.map { x =>
      val webColor = colorMap.getOrElse(x, defaultColor)
      List(x, webColor, "W20").mkString("\t")
    }.mkString("\n")
    val mapData = Map(
      "selection" -> nameStr,
      "default_opacity" -> 1.toString,
      "default_width" -> 3.toString,
      "default_radius" -> 7.toString,
      "default_color" -> "#666666",
      "background_color" -> "#ffffff",
      "tax_filter" -> "",
      "export_type" -> "svg",
      "export_dpi" -> 1200.toString,
      "include_microbial" -> 0.toString,
      "whole_pathways" -> 0.toString,
      "include_secondary" -> 0.toString,
      "whole_modules" -> 0.toString,
      "include_antibiotic" -> 0.toString,
      "keep_colors" -> 1.toString,
      "include_metabolic" -> 1.toString,
      "query_reactions" -> 0.toString
    )
    ws.url("https://pathways.embl.de/mapping.cgi").withRequestTimeout(120 seconds).post(mapData).
      flatMap { response =>
        response.status match {
          case 200 => val file = new File(parent, "out.svg")
            val outputStream = java.nio.file.Files.newOutputStream(file.toPath)
            val sink = Sink.foreach[ByteString] { bytes =>
              outputStream.write(bytes.toArray)
            }
            response.bodyAsSource.runWith(sink).andThen {
              case result =>
                outputStream.close()
                result.get
            }.map { x =>
              println(response)
              println(Utils.getTime(startTime))
              Ok("success")
            }
          case _ => Future.successful(Ok("success"))
        }


      }


  }

}
